<template>
    <!-- firstpages/authorization/indedx.wxml -->
    <view>
        <view v-if="canIUse">
            <view class="header">
                <image src="/static/images/logo.png"></image>
            </view>

            <view class="content">
                <view>申请获取以下权限</view>
                <text>获得你的公开信息(昵称、头像、手机号等)</text>
            </view>

            <button class="bottom" type="primary" open-type="getPhoneNumber" lang="zh_CN" @getphonenumber="getPhoneNumber" v-if="!bool">授权登录</button>

            <view v-if="bool" class="bottom1">授权登录</view>
        </view>
        <view v-else>请升级微信版本</view>
    </view>
</template>

<script>
// firstpages/authorization/indedx.js
const app = getApp(); // 引入app

const _request = require('../../utils/request.js');

import md5 from '../../utils/md5.js';
export default {
    data() {
        return {
            key: app.globalData.key,
            //全局img路径
            canIUse: uni.canIUse('button.open-type.getUserInfo'),
            sessionKey: '',
            openId: '',
            UserInfoObj: null,
            phoneNumber: '',
            bool: true // 防止自动登录时候点击
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        this.getUserInfo();
        let that = this; // 查看是否授权

        uni.getSetting({
            success: function (res) {
                if (res.authSetting['scope.userInfo']) {
                    uni.getUserInfo({
                        success: function (res) {
                            that.setData({
                                UserInfoObj: res.data
                            }); // 根据自己的需求有其他操作再补充
                            // 我这里实现的是在用户授权成功后，调用微信的 wx.login 接口，从而获取code

                            uni.login({
                                success: (res) => {
                                    // 获取到用户的 code 之后：res.code}
                                    // console.log(res.code,'res.code');
                                    that.getwxAppletlogin(res.code);
                                }
                            });
                        }
                    });
                } else {
                    // 用户没有授权
                }
            }
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 上传位置
        postXcxSave(latitude, longitude, city, userId) {
            _request
                .postObj('/userLocation/xcxsave', {
                    userId,
                    latitude,
                    longitude,
                    name: city
                })
                .then((res) => {})
                .catch((error) => {
                    console.log(error, 'error');
                });
        },

        // 自动绑定推荐人
        onSubmitcode(userId, token) {
            uni.request({
                url: app.globalData.baseurl + '/store-api/recomUser/bindInviteCode',
                method: 'POST',
                data: {
                    userId,
                    invitecode: uni.getStorageSync('code')
                },
                header: {
                    token
                },

                success(request) {
                    uni.removeStorageSync('code');
                }
            });
        },

        // 获取手机号码
        getPhoneNumber(e) {
            let msg = e.detail.errMsg;
            let that = this;
            let sessionID = this.sessionKey;
            let encryptedDataStr = e.detail.encryptedData;
            let iv = e.detail.iv;
            if (msg == 'getPhoneNumber:ok') {
                uni.checkSession({
                    success: function (res) {
                        that.deciyption(sessionID, encryptedDataStr, iv);
                    },
                    fail: function () {
                        uni.login({
                            success: (res) => {
                                that.getwxAppletlogin(res.code);
                                that.deciyption(sessionID, encryptedDataStr, iv);
                            }
                        });
                    }
                });
            }
        },

        deciyption(sessionID, encryptedDataStr, iv) {
            let that = this;

            _request
                .postObj('/storeUser/wxDecrypt', {
                    client: 'Applet',
                    encryptedData: encryptedDataStr,
                    iv: iv,
                    sessionKey: sessionID
                })
                .then((res) => {
                    this.setData({
                        phoneNumber: JSON.parse(res.data.data).phoneNumber
                    }); // 获取用户头像

                    uni.getUserInfo({
                        success: function (res) {
                            let headImg = res.userInfo.avatarUrl;
                            that.goLogin(that.phoneNumber, that.openId, headImg);
                        }
                    });
                });
        },

        // 获取用户信息
        getUserInfo() {
            uni.getUserProfile({
                desc: 'Wexin',
                // 这个参数是必须的
                success: (res) => {
                    console.log(res);
                },
                fail: (err) => {
                    console.log(err);
                }
            });
        },

        // 获取密钥key
        getwxAppletlogin(code) {
            _request
                .get('/storeUser/wxAppletlogin', {
                    code: code,
                    client: 'Applet'
                })
                .then((res) => {
                    this.setData({
                        sessionKey: res.data.data.sessionKey,
                        openId: res.data.data.openId
                    });

                    if (res.data.data.id) {
                        this.setData({
                            phoneNumber: res.data.data.mobile
                        });

                        if (uni.getStorageSync('code')) {
                            this.onSubmitcode(res.data.data.id, res.data.data.token);
                        }

                        uni.setStorageSync('userid', res.data.data.id);
                        uni.setStorageSync('user', res.data.data);
                        uni.setStorageSync('token', res.data.data.token);
                        uni.setStorageSync('userId', res.data.data.id);
                        uni.request({
                            url: 'https://scrm.yiyue.pub/store/addCodeUser',
                            method: 'post',
                            data: {
                                userId: res.data.data.id,
                                invitecode: uni.getStorageSync('code') || ''
                            },
                            header: {
                                'Content-Type': 'application/json',
                                token: uni.getStorageSync('token')
                            }
                        });

                        if (res.data.data.storeId && res.data.data.storeId != null) {
                            // 存在说明已经成为门店
                            uni.setStorageSync('storeId', res.data.data.storeId);
                            let router = uni.getStorageSync('Router');
                            let url = uni.getStorageSync('Url');

                            if (url || router) {
                                if (router.startsWith('/firstpages')) {
                                    uni.reLaunch({
                                        url: router
                                    });
                                } else {
                                    uni.redirectTo({
                                        url: url
                                    });
                                }

                                uni.removeStorageSync('Router');
                                uni.removeStorageSync('Url');
                            } else {
                                uni.reLaunch({
                                    url: '/firstpages/home/index'
                                });
                            } // wx.reLaunch({
                            //   url: '/firstpages/home/index',
                            // })
                        } else {
                            // 如果没有美发师id就去完善资料
                            uni.reLaunch({
                                url: '/firstpages/information/index'
                            });
                        }
                    } else {
                        this.setData({
                            bool: false
                        });
                    }
                });
        },

        // 登录
        goLogin(mobile, openId, img) {
            let signData = md5.hex(openId + '&' + mobile + '&' + this.key);

            _request
                .postObj('/storeUser/loginWXAdds', {
                    client: 'Applet',
                    headImg: img,
                    mobile: mobile,
                    openId: openId,
                    signData: signData,
                    type: 3
                })
                .then((res) => {
                    if (res.data.data) {
                        this.setData({
                            sessionKey: res.data.data.sessionKey,
                            openId: res.data.data.openId
                        });
                    }

                    if (res.data.code === 200) {
                        uni.setStorageSync('userid', res.data.data.id);
                        uni.setStorageSync('userId', res.data.data.id);
                        uni.setStorageSync('user', res.data.data);
                        uni.setStorageSync('token', res.data.data.token);

                        if (uni.getStorageSync('code')) {
                            this.onSubmitcode(res.data.data.id, res.data.data.token);
                        }

                        if (res.data.data.firstData) {
                            let status = res.data.data.firstData.firstLogin;
                        } // this.postXcxSave('22.547', '114.085947', '深圳市', res.data.data.id)

                        if (res.data.data.storeId && res.data.data.storeId != null) {
                            uni.setStorageSync('storeId', res.data.data.storeId); // wx.switchTab({
                            //   url: '/firstpages/home/index',
                            // })

                            let router = uni.getStorageSync('Router');
                            let url = uni.getStorageSync('Url');

                            if ((url || router) && !router.startsWith('/firstpages/authorization/index')) {
                                if (router.startsWith('/firstpages')) {
                                    uni.navigateTo({
                                        url: router
                                    });
                                } else {
                                    uni.redirectTo({
                                        url: url
                                    });
                                }

                                uni.removeStorageSync('Router');
                                uni.removeStorageSync('Url');
                            } else {
                                uni.switchTab({
                                    url: '/firstpages/home/index'
                                });
                            }
                        } else if (!res.data.data.storeId && res.data.data.storeId == null) {
                            uni.reLaunch({
                                url: '/firstpages/information/index'
                            });
                        } // this.checkMobile()
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none',
                            duration: 2000
                        });
                    }
                });
        },

        // 验证手机号
        checkMobile() {
            let that = this;

            _request
                .get('/user/checkMobile', {
                    mobile: this.phoneNumber
                })
                .then((res) => {});
        }
    }
};
</script>
<style>
/* firstpages/authorization/indedx.wxss */
page {
    background: #ffffff;
}
.header {
    margin: 90rpx 0 90rpx 50rpx;
    border-bottom: 1px solid #ccc;
    text-align: center;
    width: 650rpx;
    height: 300rpx;
    line-height: 450rpx;
}

.header image {
    width: 200rpx;
    height: 200rpx;
}

.content {
    margin-left: 50rpx;
    margin-bottom: 90rpx;
}

.content text {
    display: block;
    color: #9d9d9d;
    margin-top: 40rpx;
}

.bottom {
    border-radius: 80rpx;
    margin: 70rpx 50rpx;
    font-size: 35rpx;
}

.bottom1 {
    background-color: #1aad19;
    color: #fff;
    border-radius: 80rpx;
    margin: 70rpx 50rpx;
    font-size: 35rpx;
    height: 86rpx;
    width: 650rpx;
    text-align: center;
    line-height: 86rpx;
}
</style>
